package dxcTopic;

public class syn_wait_notify {


    /**
     * synchronized wait() notify()实现线程交替打印
     *
     * 问题1 两个线程执行顺序不能保证
     * @param args
     */
    public static void main(String[] args) {
        final Object o = new Object();
        int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        String[] b = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i" };


        new Thread(() -> {
            synchronized (o) {
                for (int i = 0; i < a.length; i++) {
                    System.out.print(a[i]);
                    try {
                        //一定要注意，先叫醒再休息
                        o.notify();//执行完一个打印操作就叫醒对方
                        o.wait();//让出锁，自己去休息
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                o.notify();//循环结束后 不需要进行叫醒对方操作，所以停止


            }


        }, "t1" ).start();

        new Thread(() -> {
            synchronized (o) {
                for (int j = 0; j < b.length; j++) {
                    System.out.print(b[j]);
                    try {
                        o.notify();
                        o.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                o.notify();//循环结束后 不需要进行叫醒对方操作，所以停止

            }

        }, "t2" ).start();

    }
}
